import React, { Suspense } from 'react'
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom'
import Lazy from '../pages/lazy'

// 路由表
import page from './page'

// 路由类型的接口
import { routerItem } from '../interface'

export default function Router() {

    // 拦截器
    const BeforeEach = ({ children }: { children: JSX.Element | any }) => {

        // 获取当前路由信息
        const loaction = useLocation()

        // 获取本地的token 
        const token = localStorage.getItem('token')

        if (!token && loaction.pathname !== '/login') {
            return <Navigate to='/login' />
        }

        return children
    }

    // 递归路由表
    const mapRouter = (routes: routerItem[]) => {
        // 创建新路由
        const newRoutes = routes.map((item: routerItem, idx) => {
            return item.path ? <Route key={idx} path={item.path} element={<BeforeEach> {item.element} </BeforeEach>}>
                {
                    // 判断是否存在子集，如果存在就在遍历
                    item.children && mapRouter(item.children)
                }
                {/* 路由重定向 */}
            </Route> : <Route key={idx} path={item.from} element={<Navigate to={item.to} />}></Route>
        })

        // 返回新路由表
        return newRoutes
    }

    return (
        <Suspense fallback={<Lazy />}>
                <BrowserRouter>
                    <Routes>
                        {
                            mapRouter(page)
                        }
                    </Routes>
                </BrowserRouter>

        </Suspense>

    )
}
